//
//  SQLiteManager.m
//  18-AddressBook+SQLite
//
//  Created by Snow on 16/8/8.
//  Copyright © 2016年 Snow. All rights reserved.
//

#import "SQLiteManager.h"
#import "Model.h"
@implementation SQLiteManager
+ (SQLiteManager *)sharedManger
{
    static SQLiteManager *manager = nil;
    //保证线程安全 只执行一次
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[SQLiteManager alloc] init];
    });
    return manager;
}
- (BOOL)openSQLite3WithFileName:(NSString *)name
{
    
    NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *document = [pathArray firstObject];
    //数据库SQLite3文件类型 .db
    NSString *dbPath = [document stringByAppendingPathComponent:@"DLS160710.sqlite"];
    //utf8属性 将oc字符串转换成c语言字符串
    //参数1: 数据库文件路径
    //参数2: 指向指针的指针 该指针可以被修改 数据库管理指针
    NSLog(@"%@", dbPath);
    int result = sqlite3_open([dbPath UTF8String], &dbPoint);
    //sqlite3_open 当文件路径不存在时 文件会被SQLite创建并打开
    //当路径文件存在时 会被直接打开
    //sqlite3_open 返回值为int型, 0 SQLite_OK  代表成功 , 1 代表失败 .
    //SQLite_OK
    return [self isOperationResult:result alertText:@"打开数据库"];
}
- (BOOL)isOperationResult:(int)result alertText:(NSString *)text
{
    BOOL isOperation = YES;
    if (result == SQLITE_OK) {
        NSLog(@"%@成功", text);
        isOperation = YES;
    } else {
        NSLog(@"%@失败---%d", text, result);
        isOperation = NO;
    }
    return isOperation;
}
- (BOOL)insertModel:(Model *)model
{
    NSData *data = UIImageJPEGRepresentation(model.image, 1);
    NSString *sql = [NSString stringWithFormat:@"INSERT INTO DLS160710 (name, age, phoneNumber, gender, image)  VALUES ('%@', '%@', '%@', '%@', '%@')", model.name, model.age, model.phoneNumber, model.gender, data];
    int result = sqlite3_exec(dbPoint, [sql UTF8String], NULL, NULL, NULL);
    return [self isOperationResult:result alertText:@"添加数据"];
}
- (void)createTabel {
    // 创建表格的 SQL语句.
    NSString *sql = @"CREATE  TABLE IF NOT EXISTS DLS160710(ID_S INTEGER PRIMARY KEY AUTOINCREMENT, section text, name text, age INTEGER, phoneNumber text, gender text, image blob)";
    int result = sqlite3_exec(dbPoint, sql.UTF8String, nil, nil, nil);
    
    if (result == SQLITE_OK) {
        NSLog(@"创建表格成功");
    }
    else {
        NSLog(@"创建表格失败, 错误码:%d", result);
    }
}

@end
